/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;

import Datos.Conexion;
import Datos.Global;
import Killer.jImputSimpleBox;
import Killer.jMessageFlush;
import Negocio.clsRecetaCompuesta;
import Negocio.clsRecetaSimple;
import Negocio.clsTipoReceta;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Pedro
 */
public class frmAgregarRecetaSimple extends javax.swing.JDialog {

    //Conexion conn = new Conexion();
    private DefaultTableModel dtmLista, dtmModel;
    private JTable table;
    private int cantFila, nroFilasAumentadas;
    public static boolean isCosto = false;

    public frmAgregarRecetaSimple(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setTitle("Agregar Recetas Simples");
        this.setLocationRelativeTo(null);
        this.isCosto = false;
        dtmLista = (DefaultTableModel) tbListaReceta.getModel();
        this.CargarRecetasSimples();
        this.cargar_listaRecetasComplementarias();

        // tabla auxiliar para cuando aumente o disminuya las filas de la tbListaRecetas en caso de que sea "CANCELAR"
        table = new JTable();
        dtmModel = (DefaultTableModel) table.getModel();
        dtmModel.addColumn("");
        dtmModel.addColumn("");
        dtmModel.addColumn("");
        dtmModel.addColumn("");
        dtmModel.addColumn("");
        dtmModel.addColumn("");
      
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel4 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        cbxBuscador = new javax.swing.JComboBox();
        txtBuscador = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbRecetas = new javax.swing.JTable();
        btnAgregar = new javax.swing.JButton();
        btnQuitar = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tbListaReceta = new javax.swing.JTable();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                cerrarVentana(evt);
            }
        });

        jPanel4.setBackground(new java.awt.Color(255, 204, 204));

        jPanel1.setBackground(new java.awt.Color(255, 204, 204));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Recetas Simples Registradas", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Cambria", 1, 12))); // NOI18N
        jPanel1.setFont(new java.awt.Font("Cambria", 1, 14)); // NOI18N

        jPanel2.setBackground(new java.awt.Color(255, 204, 204));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP));

        cbxBuscador.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        cbxBuscador.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Ver Todos", "Entrada", "Plato Fuerte", "Postre", "Sopa", "Pre-Elaboracion" }));
        cbxBuscador.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        cbxBuscador.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbxBuscadorActionPerformed(evt);
            }
        });

        txtBuscador.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        txtBuscador.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscadorKeyReleased(evt);
            }
        });

        jLabel1.setBackground(new java.awt.Color(255, 204, 204));
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/lupa.png"))); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(cbxBuscador, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtBuscador, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cbxBuscador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtBuscador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tbRecetas.setBackground(new java.awt.Color(255, 255, 153));
        tbRecetas.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        tbRecetas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "idReceta", "Receta", "Tipo", "Preparacion", "Costo", "Valor", "Rendimiento", "Modelo", "fecha", "restaurar", "unidad"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbRecetas.setRowHeight(20);
        tbRecetas.setSelectionBackground(new java.awt.Color(0, 204, 51));
        jScrollPane1.setViewportView(tbRecetas);
        tbRecetas.getColumnModel().getColumn(0).setMinWidth(0);
        tbRecetas.getColumnModel().getColumn(0).setPreferredWidth(0);
        tbRecetas.getColumnModel().getColumn(0).setMaxWidth(0);
        tbRecetas.getColumnModel().getColumn(1).setPreferredWidth(150);
        tbRecetas.getColumnModel().getColumn(2).setMinWidth(0);
        tbRecetas.getColumnModel().getColumn(2).setPreferredWidth(0);
        tbRecetas.getColumnModel().getColumn(2).setMaxWidth(0);
        tbRecetas.getColumnModel().getColumn(3).setMinWidth(0);
        tbRecetas.getColumnModel().getColumn(3).setPreferredWidth(0);
        tbRecetas.getColumnModel().getColumn(3).setMaxWidth(0);
        tbRecetas.getColumnModel().getColumn(4).setPreferredWidth(30);
        tbRecetas.getColumnModel().getColumn(5).setPreferredWidth(30);
        tbRecetas.getColumnModel().getColumn(6).setMinWidth(0);
        tbRecetas.getColumnModel().getColumn(6).setPreferredWidth(0);
        tbRecetas.getColumnModel().getColumn(6).setMaxWidth(0);
        tbRecetas.getColumnModel().getColumn(7).setMinWidth(0);
        tbRecetas.getColumnModel().getColumn(7).setPreferredWidth(0);
        tbRecetas.getColumnModel().getColumn(7).setMaxWidth(0);
        tbRecetas.getColumnModel().getColumn(8).setMinWidth(0);
        tbRecetas.getColumnModel().getColumn(8).setPreferredWidth(0);
        tbRecetas.getColumnModel().getColumn(8).setMaxWidth(0);
        tbRecetas.getColumnModel().getColumn(9).setMinWidth(0);
        tbRecetas.getColumnModel().getColumn(9).setPreferredWidth(0);
        tbRecetas.getColumnModel().getColumn(9).setMaxWidth(0);
        tbRecetas.getColumnModel().getColumn(10).setMinWidth(0);
        tbRecetas.getColumnModel().getColumn(10).setPreferredWidth(0);
        tbRecetas.getColumnModel().getColumn(10).setMaxWidth(0);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE))
        );

        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/next2.png"))); // NOI18N
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/forward2.png"))); // NOI18N
        btnQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnQuitarActionPerformed(evt);
            }
        });

        jPanel3.setBackground(new java.awt.Color(255, 204, 204));
        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Lista Recetas Complementarias", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Cambria", 1, 12))); // NOI18N

        tbListaReceta.setBackground(new java.awt.Color(204, 255, 204));
        tbListaReceta.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        tbListaReceta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "idReceta", "Receta", "Costo Total", "Valor Proteico", "Cantidad", "Unidad"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbListaReceta.setGridColor(new java.awt.Color(0, 0, 204));
        tbListaReceta.setRowHeight(20);
        tbListaReceta.setSelectionBackground(new java.awt.Color(51, 255, 102));
        tbListaReceta.setSelectionForeground(new java.awt.Color(0, 0, 0));
        jScrollPane3.setViewportView(tbListaReceta);
        tbListaReceta.getColumnModel().getColumn(0).setMinWidth(0);
        tbListaReceta.getColumnModel().getColumn(0).setPreferredWidth(0);
        tbListaReceta.getColumnModel().getColumn(0).setMaxWidth(0);
        tbListaReceta.getColumnModel().getColumn(1).setPreferredWidth(150);
        tbListaReceta.getColumnModel().getColumn(2).setPreferredWidth(20);
        tbListaReceta.getColumnModel().getColumn(3).setPreferredWidth(25);
        tbListaReceta.getColumnModel().getColumn(4).setPreferredWidth(15);
        tbListaReceta.getColumnModel().getColumn(5).setPreferredWidth(50);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 566, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        btnAceptar.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        btnAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/icon_accept.gif"))); // NOI18N
        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnCancelar.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/action_stop.gif"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnQuitar, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 597, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnAgregar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnQuitar)
                .addGap(229, 229, 229))
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAceptar)
                    .addComponent(btnCancelar))
                .addContainerGap(16, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cbxBuscadorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxBuscadorActionPerformed
        if (clsTipoReceta.isBuscador) {
            String tipoReceta = cbxBuscador.getSelectedItem().toString();
            String sql;  //para cargar la tabla segun seleccione  el tipo de receta del CBX
            if (tipoReceta.equals("Ver Todos")) {
                sql = "CALL `obtener_ListaRecetasSimp`(" + 3 + ")";
            } else {
                sql = "CALL `buscador_RecetaSimple`(" + "''," + '"' + tipoReceta + '"' + "," + 8 + ")";
            }
            clsRecetaSimple.mostrarTablaRecetasSimples(tbRecetas, sql);
        }
    }//GEN-LAST:event_cbxBuscadorActionPerformed

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        for (int f = 0; f < tbRecetas.getRowCount(); f++) {
            if (tbRecetas.isRowSelected(f)) {
                Object[] o = new Object[6];
                int id_Receta = (int) tbRecetas.getValueAt(f, 0);
                String nombreReceta = (String)tbRecetas.getValueAt(f, 1);
                String unidad = (String)tbRecetas.getValueAt(f, 10);
                o[0] = id_Receta;
                
                if (!existeIdReceta(id_Receta) || tbListaReceta.getRowCount() == 0) {
                    jImputSimpleBox.showSimpleBox("Ingrese la cantidad que  ocupara de la receta " + nombreReceta+" en "+'"'+unidad+'"', "");
                    if (jImputSimpleBox.btnAceptar) {
                        o[1] = nombreReceta;
                        float cantidad = Float.valueOf(jImputSimpleBox.txtCantidad);
                        float costoTot = costoVerdadero((float) tbRecetas.getValueAt(f, 4),(float)tbRecetas.getValueAt(f, 6),cantidad);  //costoTot,cantTotal,porcion
                        float valorProt = valorProteicoTotal((float)tbRecetas.getValueAt(f, 5),(float)tbRecetas.getValueAt(f, 6),cantidad);
                        o[2] = costoTot;
                        o[3] = valorProt;
                        o[4] = cantidad;
                        o[5] = tbRecetas.getValueAt(f, 10);
                        
                        dtmLista.addRow(o);
                        clsRecetaCompuesta.insertar_Compuesta(frmReceta.IdRecetaSimple, id_Receta,cantidad,unidad);  // idrecetaSimple,idRecetaComplementaria

                        nroFilasAumentadas++;

                        frmReceta.costoTotal += costoTot;    // suma el costo total de la receta
                        frmReceta.valorProteico += valorProt;   // suma el valor proteico de la receta
                    }
                } else {
                    jMessageFlush.showMessageFlush("Ya existe   la receta " + '"' + tbRecetas.getValueAt(f, 1).toString() + '"' + "en la lista de Recetas", jMessageFlush.shortTime, jMessageFlush.Warning);
                }

            }

        }
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuitarActionPerformed
        int f = 0;
        while (f < tbListaReceta.getRowCount()) {
            if (tbListaReceta.isRowSelected(f)) {
                frmReceta.costoTotal += (float) tbListaReceta.getValueAt(f, 2);    // suma el costo total de la receta
                frmReceta.valorProteico += (float) tbListaReceta.getValueAt(f, 3);
                dtmModel.addRow(obtener_filaEliminada(f));
                clsRecetaCompuesta.eliminar_recetaComplementaria(frmReceta.IdRecetaSimple,(int) tbListaReceta.getValueAt(f, 0));

                dtmLista.removeRow(f);
            } else {
                f++;
            }
        }
    }//GEN-LAST:event_btnQuitarActionPerformed

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        frmReceta.cbxComplementario.removeAllItems();
        for (int f = 0; f < tbListaReceta.getRowCount(); f++) {
            frmReceta.cbxComplementario.addItem(tbListaReceta.getValueAt(f, 1));
        }

        Global.costoTotalComplem = frmReceta.costoTotal;
        Global.valorTotalComplem = frmReceta.valorProteico;
        frmReceta.lblCostoReceta.setText(String.valueOf(frmReceta.costoTotal+Global.costoTotalSimple));
        frmReceta.lblValorProteico.setText(String.valueOf(frmReceta.valorProteico+Global.valorTotalSimple));
        this.dispose();
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void txtBuscadorKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscadorKeyReleased
        String NombreReceta = txtBuscador.getText();
        String tipoReceta = cbxBuscador.getSelectedItem().toString();
        String sql; //para cargar la tabla segun vaya tecleando
        if (tipoReceta.equals("Ver Todos")) {
            sql = "CALL`buscador_RecetaSimple`(" + '"' + NombreReceta + '"' + ",''," + 9 + ")";
        } else {
            sql = "CALL`buscador_RecetaSimple`(" + '"' + NombreReceta + '"' + "," + '"' + tipoReceta + '"' + "," + 7 + ")";
        }
        clsRecetaSimple.mostrarTablaRecetasSimples(tbRecetas, sql);
    }//GEN-LAST:event_txtBuscadorKeyReleased

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        if (cantFila > tbListaReceta.getRowCount()) {
            // si disminuyeron filas
            this.aumentarFilasEliminadas();
        } else {
            // si aumentaron filas
            this.eliminarFilasAumentadas();
        }
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void cerrarVentana(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_cerrarVentana
        if (cantFila > tbListaReceta.getRowCount()) {
            // si disminuyeron filas
            this.aumentarFilasEliminadas();
        } else {
            // si aumentaron filas
            this.eliminarFilasAumentadas();
        }
    }//GEN-LAST:event_cerrarVentana

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmAgregarRecetaSimple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmAgregarRecetaSimple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmAgregarRecetaSimple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmAgregarRecetaSimple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                frmAgregarRecetaSimple dialog = new frmAgregarRecetaSimple(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnQuitar;
    private javax.swing.JComboBox cbxBuscador;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable tbListaReceta;
    private javax.swing.JTable tbRecetas;
    private javax.swing.JTextField txtBuscador;
    // End of variables declaration//GEN-END:variables

    private void CargarRecetasSimples() {
        String sql = "CALL `obtener_listaRecetasSimp`(" + 2 + ")";
        clsRecetaSimple.mostrarTablaRecetasSimples(tbRecetas, sql);

        clsTipoReceta.cargarTipoRecetaBuscador(cbxBuscador);

    }

    private void cargar_listaRecetasComplementarias() {
         Global.limpiarTabla(tbListaReceta);
        try {
            String sql = "CALL `obtener_listaRecetaComplementaria`(" + frmReceta.IdRecetaSimple + ")";
            ResultSet rs = Conexion.executeQuery(Conexion.conn, sql, null);
            while (rs.next()) {
                Object[] receta = new Object[6];
                receta[0]=rs.getInt(1);
                receta[1]=rs.getString(2);
                float costo=costoVerdadero(rs.getFloat(3),rs.getFloat(7) ,rs.getFloat(5) );
                float valor =valorProteicoTotal(rs.getFloat(4),rs.getFloat(7) ,rs.getFloat(5));
                receta[2]=costo;
                receta[3]=valor;
                receta[4]=rs.getFloat(5);
                receta[5]=rs.getString(6);
                        
                dtmLista.addRow(receta);
                
                frmReceta.costoTotal += costo;
                frmReceta.valorProteico += valor;
            }
            cantFila = tbListaReceta.getRowCount();
            nroFilasAumentadas = 0;
        } catch (SQLException ex) {
            System.out.println("error al cargar tabla ingredientes " + ex);
        }
    }

    private boolean existeIdReceta(int id_Receta) {
        List<Integer> L = new ArrayList<>();
        for (int i = 0; i < tbListaReceta.getRowCount(); i++) {
            L.add((Integer) tbListaReceta.getValueAt(i, 0));
        }
        return L.contains(id_Receta);
    }

    private Object[] obtener_filaEliminada(int fila) {
        Object[] o = new Object[6];
        for (int c = 0; c < tbListaReceta.getColumnCount(); c++) {
            o[c] = tbListaReceta.getValueAt(fila, c);
        }
        return o;
    }

    private void eliminarFilasAumentadas() {
        int k = tbListaReceta.getRowCount();
        for (int f = 0; f < nroFilasAumentadas; f++) {
            clsRecetaCompuesta.eliminar_recetaComplementaria((int) tbListaReceta.getValueAt(k - 1, 0), frmReceta.IdRecetaSimple);
            frmReceta.costoTotal -= (float) tbListaReceta.getValueAt(k - 1, 4);
            frmReceta.valorProteico -= (float) tbListaReceta.getValueAt(k - 1, 5);
            dtmLista.removeRow(k - 1);
            k--;
        }
        nroFilasAumentadas = 0;
    }

    private void aumentarFilasEliminadas() {
        for (int i = 0; i < table.getRowCount(); i++) {
            Object[] o = new Object[6];
            o[0] = table.getValueAt(i, 0);
            o[1] = table.getValueAt(i, 1);
            o[2] = table.getValueAt(i, 2);
            o[3] = table.getValueAt(i, 3);
            o[4] = table.getValueAt(i, 4);
            o[5] = table.getValueAt(i, 5);
            
            dtmLista.addRow(o);
            clsRecetaCompuesta.insertar_Compuesta(frmReceta.IdRecetaSimple, 
                                                 (int) table.getValueAt(i, 0),
                                                 (float)table.getValueAt(i, 2),
                                                 (String)table.getValueAt(i, 3));  // idrecetaSimple,idRecetaComplementaria
            frmReceta.costoTotal += (float) table.getValueAt(i, 2);
            frmReceta.valorProteico += (float) table.getValueAt(i, 3);
        }
        Global.limpiarTabla(table);
    }
    
    public  static   float costoVerdadero(float costoInsumo, float cantidadInsumo, float cantidadPorcion) {
        return (cantidadPorcion * costoInsumo) / cantidadInsumo;
    }

    public static   float valorProteicoTotal(float valorProteicoInsumo, float valorInsumo, float cantidad) {
        return (cantidad * valorProteicoInsumo) / valorInsumo;
    }
}
